const express = require('express');
const app = express();

const prizes = [{
    id: '0x01',
    title: '谢谢参与',
    img: 'https://s1.ax1x.com/2022/04/28/LOuhJs.png',
}, {
    id: '0x02',
    title: '优惠券',
    img: 'https://s1.ax1x.com/2022/04/28/LOu4Wn.png',
}, {
    id: '0x03',
    title: '50元话费',
    img: 'https://s1.ax1x.com/2022/04/28/LOKPeO.png',
}, {
    id: '0x04',
    title: '20元话费',
    img: 'https://s1.ax1x.com/2022/04/28/LOKPeO.png',
}, {
    id: '0x05',
    title: '10元话费',
    img: 'https://s1.ax1x.com/2022/04/28/LOKPeO.png',
}, {
    id: '0x06',
    title: '10元话费',
    img: 'https://s1.ax1x.com/2022/04/28/LOKPeO.png',
}, {
    id: '0x07',
    title: '100元话费',
    img: 'https://s1.ax1x.com/2022/04/28/LOKPeO.png',
}, {
    id: '0x08',
    title: '10积分',
    img: 'https://s1.ax1x.com/2022/04/28/LOuoQ0.png',
}];
let recordlist = [];    //中奖记录
let freeNum = 9999; //免费抽奖次数，初始化为9999
let isWin = false;  //是否中奖
let prizeId = '';

// 生成随机数函数
getRandomNum = (min, max) => {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

// 对不同奖品设置概率，抽出奖品Id
getPrizeId = () => {
    const num = getRandomNum(1, 100);
    if (num >= 1 && num <= 50) return prizes[0].id;
    if (num >= 51 && num <= 70) return prizes[7].id;
    if (num >= 71 && num <= 80) return prizes[1].id;
    if (num >= 81 && num <= 87) return prizes[4].id;
    if (num >= 88 && num <= 94) return prizes[5].id;
    if (num >= 95 && num <= 97) return prizes[3].id;
    if (num == 98 || num == 99) return prizes[2].id;
    if (num == 100) return prizes[6].id;
}

app.get('/', (req, res) => {
    res.send('hello world')
})

// 返回初始化信息
app.get('/prizes', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.json({
        prizes: prizes,
        freeNum: freeNum,
        rounds: 6
    })
})

//返回抽奖结果
app.get('/prize/id', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');

    prizeId = getPrizeId();
    isWin = prizeId === prizes[0].id ? false : true;
    if (freeNum > 0) freeNum--;

    res.json({
        prizeId: prizeId,
        isWin: isWin,
        freeNum: freeNum
    })
})

// 返回中奖记录
app.get('/records', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');

    res.json({
        records: recordlist,
    })
})

// 添加中奖记录
app.get('/confirm', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');

    if (isWin) {//若中奖，添加中奖记录信息
        const record = prizes.find(item => item.id === prizeId);
        recordlist = [record, ...recordlist];
    }

    res.json({
        res: 'ok'
    })
})

app.listen(5000, "localhost", (err) => {
    if (err) {
        console.log(err)
    } else {
        console.log('服务已启动，5000端口正在监听...')
    }
})